// pages/video/video.js
//获取应用实例
const app = getApp()
let utils = require('../../../utils/util.js')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    verCodeList: [], //验证码数组
    verCodeCount: null, //验证码个数，用于兼容多个验证码
    isShowPop: false, //是否显示弹窗
    isShowMask: false, //是否显示遮罩
    isShowCamera: false, //是否显示照相机
    cameraTime: 6, //视频录制总时间
    firstVerCode: '·', //第一个验证码
    secondVerCode: '·', //第二个验证码
    thirdVerCode: '·', //第三个验证码
    fourVerCode: '·', //第四个验证码
    ctx: null, //相机对象
    recorderManager: null, //录音
    IdCardImage: '', //身份证名称
    ErrCode: 0, //错误码
    isShowCoverText: true, //验证码之前的提示语
    isShowLoading: false, //是否显示加载中
    loadingText: '视频识别中...', //加载中文本显示
    isAuthority: false //是否开通声音授权
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //console.log('onload');
    let self = this;
    //获取身份证正面照名称
    self.setData(options);

    if (utils.isNullOrEmpty(self.data.IdCardImage)) {
      self.data.IdCardImage = wx.getStorageSync('IdCardImage') || '';
    }
    //console.log(self.data.IdCardImage)

    //查询是否获取相机权限
    //这里需要进行录音授权
    self.isGetAuthority();
  },
  /**
   *  是否开通授权
   */
  isGetAuthority: function() {
    //console.log('是否开通授权');
    let self = this;
    wx.getSetting({
      success(res) {
        //判断是否获取录音权限
        if (!res.authSetting['scope.record']) {
          //console.log('用户没有授权录音权限');
          //没有授权录音就先进行授权
          wx.authorize({
            scope: 'scope.record',
            success() {
              //console.log('录音授权成功');
              let ctx = wx.createCameraContext();
              let recorderManager = wx.getRecorderManager();
              self.setData({
                isAuthority: true,
                ctx: ctx,
                recorderManager: recorderManager
              });
            },
            fail() {
              self.openConfirm();
              self.setData({
                isAuthority: false
              })
            }
          });
        } else {
          //console.log('用户已经授权录音');
          let ctx = wx.createCameraContext();
          let recorderManager = wx.getRecorderManager();
          self.setData({
            isAuthority: true,
            ctx: ctx,
            recorderManager: recorderManager
          });
        }
      }
    });
  },

  /**
   *  提示用户开通授权
   */
  openConfirm: function() {
    let self = this;
    wx.showModal({
      title: '提示',
      content: '身份认证需要您同意录音授权，检测到您没打开车管通的录音权限，是否去设置打开？',
      success(res) {
        if (res.confirm) {
          //console.log('用户点击确定');
          wx.openSetting({
            success: (res) => {
              if (res.authSetting['scope.record']) {
                //用户同意录音授权
                let ctx = wx.createCameraContext();
                let recorderManager = wx.getRecorderManager();
                self.setData({
                  recorderManager: recorderManager,
                  ctx: ctx,
                  isAuthority: true
                });
              } else {
                //用户拒绝录音授权
                self.setData({
                  isAuthority: false
                })
              }
            }
          })
        } else if (res.cancel) {
          //console.log('用户点击取消');
          self.setData({
            isAuthority: false
          })
        }
      }
    })

  },
  /**
   *  点击下一步
   */
  goNextTap: function() {
    let self = this;
    let isAuthority = self.data.isAuthority;
    //用户是否同意了录音授权
    if (isAuthority) {
      //如果同意了授权，进行弹层到下一步
      self.setData({
        isShowPop: true,
        isShowMask: true,
      })
    } else {
      //如果没有同意授权，弹出模态框
      self.openConfirm();
    }

  },
  /**
   *  弹窗按钮点击
   */
  popBtnTap: function() {
    let self = this;
    self.showVerCode();
  },
  /**
   * 显示验证码
   */
  showVerCode() {
    let self = this;
    //console.log("app.userInfo.AuthLevel:" + app.userInfo.AuthLevel);
    self.setData({
      isShowPop: false,
      isShowMask: false,
      isShowCamera: true
    })
    let verCodeList = self.data.verCodeList; //验证码数组
    let cameraTime = self.data.cameraTime; //摄像头录像的时间
    let firstVerCode = verCodeList[0]; //第一个验证码
    let secondVerCode = verCodeList[1]; //第二个验证码
    let thirdVerCode = verCodeList[2]; //第三个验证码
    let fourVerCode = verCodeList[3]; //第四个验证码
    let timer = setInterval(function() {
      cameraTime--;
      if (cameraTime == 5) {
        if (app.userInfo.AuthLevel == 1) { //身份证认证
          self.startRecord();
          self.startRecorder();
        } else if (app.userInfo.AuthLevel == 2) { //语音认证
          self.startRecord(); //开始视频         
        } else { //视频认证
          self.startRecorder(); //开始录音         
        }

        self.setData({
          // 控制提示语的显示隐藏放在这里控制，看你想怎么控制
          isShowCoverText: false,
          firstVerCode: firstVerCode
        });
      } else if (cameraTime == 4) {
        self.setData({
          secondVerCode: secondVerCode
        })
      } else if (cameraTime == 3) {
        self.setData({
          thirdVerCode: thirdVerCode
        })
      } else if (cameraTime == 2) {
        self.setData({
          fourVerCode: fourVerCode
        })
      }
      if (cameraTime <= 0) {
        clearInterval(timer);
        self.setData({
          isShowCamera: false,
          isShowCoverText: true,
          firstVerCode: '·',
          secondVerCode: '·',
          thirdVerCode: '·',
          fourVerCode: '·'
        });
        //console.log('app.userInfo.AuthLevel', app.userInfo.AuthLevel);
        if (app.userInfo.AuthLevel == 1) { //身份证认证
          //console.log('用户等级为1');
          self.stopRecord(); //停止录制视频
          self.stopRecorder(); //停止录制音频
          // 停止录制视频和音频以后显示loading
          self.setData({
            isShowLoading: true
          })
        } else if (app.userInfo.AuthLevel == 2) { //语音认证
          self.stopRecord(); //停止录制视频
          // 停止录制视频以后显示loading
          self.setData({
            isShowLoading: true
          })
        } else { //视频认证
          self.stopRecorder(); //停止录制音频
          // 停止录制音频以后显示loading
          self.setData({
            isShowLoading: true
          })
        }
      }
    }, 1000);
  },
  /**
   * 开始录制视频
   */
  startRecord() {
    var self = this;
    if (self.data.ctx == null) {
      self.data.ctx = wx.createCameraContext(this);
    }
    self.data.ctx.startRecord({
      success: (res) => {
        //console.log('视频录制开始成功');
      },
      fail(e) {
        //console.log(e)
      }
    })
  },
  /**
   * 停止录制视频
   */
  stopRecord() {
    var self = this;
    self.data.ctx.stopRecord({
      success: (res) => {
        //console.log('停止录制视频成功');
        self.fileVideoUpload(res.tempVideoPath);
      },
      fail: (e) => {
        //console.log(e);
      }
    })
  },
  /**
   * 上传视频
   */
  fileVideoUpload(tempFilePath) {
    let self = this;
    console.log('上传视频');
    const url = app.apiBaseUrl + '/AuthenticationAI/FaceCompare';
    const uploadTask = wx.uploadFile({
      url: url, //仅为示例，非真实的接口地址
      filePath: tempFilePath,
      name: 'file',
      formData: {
        'UserID': app.userInfo.UserID, //用户
        'IdCardImage': self.data.IdCardImage
      },
      success: function(res) {
        //console.log('视频上传成功');
        var data = JSON.parse(res.data);
        //console.log(data);
        self.dealResult(data,'视频');
      },
      fail: function(res) {
        //关闭loading
        self.setData({
          isShowLoading: false
        });
        console.log(res);
      }
    });

    uploadTask.onProgressUpdate((res) => {
      //console.log('视频上传进度', res.progress)
      //console.log('视频已经上传的数据长度', res.totalBytesSent)
      //console.log('视频预期需要上传的数据总长度', res.totalBytesExpectedToSend)
    })
  },
  /**
   * 录制语音
   */
  startRecorder() {
    const self = this;
    if (self.data.recorderManager == null) {
      self.data.recorderManager = wx.getRecorderManager();
    }
    //console.log('录制语音');
    const options = {
      duration: 10000,
      sampleRate: 16000,
      numberOfChannels: 1,
      encodeBitRate: 96000,
      format: 'mp3',
      frameSize: 50
    }
    self.data.recorderManager.start(options)
  },
  /**
   * 停止录音语音
   */
  stopRecorder() {
    //console.log('停止录音语音');
    const self = this;
    self.data.recorderManager.stop();
    //停止录音监听事件
    self.data.recorderManager.onStop((res) => {
      //console.log('recorder stop', res)
      self.fileRecorderUpload(res.tempFilePath);
    });
  },
  /**
   * 上传语音
   */
  fileRecorderUpload(tempFilePath) {
    console.log('上传语音');
    const self = this;
    const url = app.apiBaseUrl + '/AuthenticationAI/ASR';
    const uploadTask = wx.uploadFile({
      url: url, //仅为示例，非真实的接口地址
      filePath: tempFilePath,
      name: 'file',
      formData: {
        'UserID': app.userInfo.UserID, //用户
        'VerCode': self.data.verCodeList.join('')
      },
      success: function(res) {
        //console.log('音频上传成功');
        var data = JSON.parse(res.data);

        self.dealResult(data,"语音");
      },
      fail: function(res) {
        //关闭loading
        self.setData({
          isShowLoading: false
        });
        console.log(res);
      }
    });

    uploadTask.onProgressUpdate((res) => {
      //console.log('语音上传进度', res.progress)
      //console.log('语音已经上传的数据长度', res.totalBytesSent)
      //console.log('语音预期需要上传的数据总长度', res.totalBytesExpectedToSend)
    })
  },
  /**
   * 获取随机字符串
   */
  getRandomArr() {
    let $chars = '0417238956';　　
    let maxPos = 10;　
    let arr = [];　　
    for (let i = 0; i < 4; i++) {
      let ch = $chars.charAt(Math.floor(Math.random() * maxPos));
      arr.push(ch);　　
    }
    return arr;
  },
  /**
   * 处理结果
   */
  dealResult(rt,ftype) {
    let self = this;
    console.log(ftype);
    console.log(rt);
    console.log("app.userInfo.AuthLevel:" + app.userInfo.AuthLevel)
    if (app.userInfo.AuthLevel == 1) { //身份证认证
      if (rt.status == 0) {
        app.setUserInfo(app.userInfo);
        app.userInfo.AuthLevel = rt.data;
        if (self.data.ErrCode != 0) {
          //关闭loading
          self.setData({
            isShowLoading: false
          });
          wx.navigateTo({
            url: "/pages/liveAuthentication/fail/fail?failCode=" + self.data.ErrCode
          });
          self.data.ErrCode = 0;
        }

      } else {
        if (self.data.ErrCode == 0) {
          self.data.ErrCode = rt.status;
        } else {
          //关闭loading
          self.setData({
            isShowLoading: false
          });
          wx.navigateTo({
            url: "/pages/liveAuthentication/fail/fail?failCode=" + rt.status
          });
          self.data.ErrCode = 0;
        }
      }
    } else { //其他
      //关闭loading
      self.setData({
        isShowLoading: false
      });
      if (rt.status == 0) {
        app.setUserInfo(app.userInfo);
        app.userInfo.AuthLevel = 4;
        wx.navigateTo({
          url: "/pages/liveAuthentication/success/success"
        })
      } else {
        wx.navigateTo({
          url: "/pages/liveAuthentication/fail/fail?failCode=" + rt.status
        })
      }
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let self = this;
    self.data.ErrCode = 0;
    //获取随机字符串
    let verCodeList = self.getRandomArr();
    self.setData({
      verCodeList: verCodeList,
      verCodeCount: verCodeList.length
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})